package com.codeyang.controller;

import com.codeyang.domain.SysMenu;
import com.codeyang.model.MenuAndAuth;
import com.codeyang.service.SysMenuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 描述:
 *
 * @author CodeYang_Site
 * @version 2021/5/24 11:14
 */
@Api(tags = "菜单管理接口")
@RequestMapping("sys/menu")
@RestController
public class MenuController {


    @Autowired
    private SysMenuService sysMenuService;

    /**
     * desc:菜单树的加载
     * 根据用户id查询用户的菜单和权限集合
     * base: 前后端分离,需要直接返回一个vo对象,包含用户的 menu和 auth 来动态渲染
     * 1.获取当前用户的id 直接从security中去拿 -是LocalThreadMap 是线程安全的拿
     * 2.查询DB
     * 3.封装菜单权限树 -->追忆缓存
     *
     * @return
     */
    @ApiOperation("根据用户id查询用户的菜单和权限集合")
    @GetMapping("nav")
    public ResponseEntity<MenuAndAuth> loadMenuAuth() {
        //1.拿userid
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        //之前已经把用户名---改为id 存到角色身份中了
        String userId = authentication.getPrincipal().toString();
        //查询DB
        List<SysMenu> sysMenuList = sysMenuService.findMenuById(userId);
        //直接从当前登录用户中拿到权限 -- 之前在登录时 已经交给UserDetails中去做了设置
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        //转换权限为 看的懂的 List<String>
        List<String> auths = authorities.stream()
                .map(Objects::toString)
                .collect(Collectors.toList());
        //组装数据返回结果
        MenuAndAuth menuAndAuth = new MenuAndAuth(sysMenuList, auths);
        return ResponseEntity.ok(menuAndAuth);
    }
}
